import axios from 'axios'
import { Indicator } from 'mint-ui'

const GUID = () => {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
}

// 创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API, // api 的 base_url
    timeout: 30000, // 请求超时时间
    headers: { id: GUID() }
})

var loadingKey = 0
// request拦截器
service.interceptors.request.use(config => {
    if (config.loading || config.loading === 0) {
        loadingKey = 1
        Indicator.open({
            text: typeof config.loading === 'string' ? config.loading : '加载中···',
            spinnerType: "fading-circle"
        });
    }
    // 加载动画在这里处理
    return config
})

// response 拦截器
service.interceptors.response.use(
    res => {
        if (loadingKey === 1) {
            Indicator.close()
            loadingKey = 0
        }
        res = res.data
        return res
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
